package com.xiaolin.springsecurity.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xiaolin.springsecurity.mapper.SystemUserMapper;
import com.xiaolin.springsecurity.model.CustomUserDetails;
import com.xiaolin.springsecurity.model.SystemUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author xiaolin
 * @Description 自定义用户认证管理器
 * @email xiaolin@gmail.com
 * @date 2024/5/4 12:11
 */
@Service
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private SystemUserMapper systemUserMapper;

    /**
     * 验证用户信息
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SystemUser systemUser = systemUserMapper.selectOne(new LambdaUpdateWrapper<SystemUser>()
                .eq(SystemUser::getUsername, username));
        if (systemUser == null) {
            throw new UsernameNotFoundException(username);
        } else {
            return new CustomUserDetails(systemUser);
        }
    }

    public static void main(String[] args) {
        // BCryptPasswordEncoder 对密码进行加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode("123456");
        System.out.println(password);
    }
}
